package com.ruoyi.common.utils.stock;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.IpUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpClientUtil;
import com.ruoyi.common.utils.http.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 获取地址类
 *
 * @author ruoyi
 */
public class SectorMarkupSortUtils {

    private static final Logger log = LoggerFactory.getLogger(SectorMarkupSortUtils.class);

    public static String[] getSectorMarkupSortBystockID(String stockID) {

        String oneUrl = "https://apparticle.longhuvip.com/w1/api/index.php";
        String oneJson = "a=GetConceptJXBKw23&apiv=w39&c=StockF10Basic&StockID=" + stockID + "&PhoneOSNew=1&DeviceID=c6b240b6-aa62-371d-9f1b-45c09dff494e&VerSion=5.18.0.2&";
        // 设置请求头
        HashMap<String, String> oneHeaders = new HashMap<>();
        oneHeaders.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        oneHeaders.put("User-Agent", "Dalvik/2.1.0 (Linux; U; Android 9; NX627J Build/PQ3B.190801.01161429)");
        oneHeaders.put("Host", "apparticle.longhuvip.com");
        oneHeaders.put("Connection", "Keep-Alive");
        oneHeaders.put("Accept-Encoding", "gzip");
        String oneContent = null;
        JSONObject oneJsonObject = null;
        try {
            oneContent = HttpClientUtil.doPost(oneUrl, oneJson, oneHeaders);
            oneJsonObject = JSON.parseObject(oneContent);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        JSONArray oneListJSONArray = oneJsonObject.getJSONArray("List");

        HashMap<String, String> CCodeArrayMap = new HashMap<>();
        for (int i = 0; i < oneListJSONArray.size(); i++) {
            JSONObject oneListJSONObject = oneListJSONArray.getJSONObject(i);
            String CCode = oneListJSONObject.getString("CCode");
            String CName = oneListJSONObject.getString("CName");

            CCodeArrayMap.put(CCode, CName);
        }


        //按照板块涨幅筛选
        HashMap<String, BigDecimal> markupSectorHashMap = new HashMap<>();
        for (Map.Entry<String, String> CCodeArrayMapEntry : CCodeArrayMap.entrySet()) {
            String CCode = CCodeArrayMapEntry.getKey();
            String twoUrl = "https://apphis.longhuvip.com/w1/api/index.php";
            String twoJson = "st=630&a=GetPlateKLineDay&c=ZhiShuKLine&PhoneOSNew=1&DeviceID=c6b240b6-aa62-371d-9f1b-45c09dff494e&VerSion=5.18.0.2&Token=d3ba72277b381ee11f3b9f3087e1cee8&Index=0&apiv=w39&Type=d&StockID=" + CCode + "&UserID=2692604&";
            // 设置请求头
            HashMap<String, String> twoHeaders = new HashMap<>();
            twoHeaders.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            twoHeaders.put("User-Agent", "Dalvik/2.1.0 (Linux; U; Android 9; NX627J Build/PQ3B.190801.01161429)");
            twoHeaders.put("Host", "apphis.longhuvip.com");
            twoHeaders.put("Connection", "Keep-Alive");
            twoHeaders.put("Accept-Encoding", "gzip");
            String twoContent = null;
            try {
                twoContent = HttpClientUtil.doPost(twoUrl, twoJson, twoHeaders);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            JSONObject twoJsonObject = JSON.parseObject(twoContent);
            JSONArray twoYJSONArray = twoJsonObject.getJSONArray("y");
            if(twoYJSONArray == null){
                continue;
            }
            if (twoYJSONArray.size() > 0) {
                if (twoYJSONArray.size() >= 2) {
                    JSONArray oneJSONArray = twoYJSONArray.getJSONArray(twoYJSONArray.size() - 2);
                    JSONArray twoJSONArray = twoYJSONArray.getJSONArray(twoYJSONArray.size() - 1);
                    BigDecimal oneJBigDecimal = new BigDecimal(oneJSONArray.get(1).toString());
                    BigDecimal twoJBigDecimal = new BigDecimal(twoJSONArray.get(1).toString());
                    BigDecimal oneIncrease = (twoJBigDecimal.subtract(oneJBigDecimal)).divide(oneJBigDecimal, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
                    markupSectorHashMap.put(CCode, oneIncrease);
                } else {
                    JSONArray oneJSONArray;
                    try {
                        oneJSONArray = twoYJSONArray.getJSONArray(twoYJSONArray.size() - 1);
                    } catch (RuntimeException e) {
                        throw new RuntimeException(e);
                    }

                    BigDecimal oneJBigDecimal = new BigDecimal(oneJSONArray.get(1).toString());
                    BigDecimal twoJBigDecimal = new BigDecimal(oneJSONArray.get(2).toString());
                    BigDecimal oneIncrease = (twoJBigDecimal.subtract(oneJBigDecimal))
                            .divide(oneJBigDecimal, 4, BigDecimal.ROUND_HALF_UP)
                            .multiply(new BigDecimal(100));
                    markupSectorHashMap.put(CCode, oneIncrease);
                }
            }


        }


        // 降序排序并取前4
        LinkedHashMap<String, BigDecimal> top4MarkupSectorHashMap = markupSectorHashMap
                .entrySet()
                .stream()
                .sorted(Map.Entry.<String, BigDecimal>comparingByValue()
                        .reversed())
                .limit(4)
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldVal, newVal) -> oldVal, LinkedHashMap::new));

        // 降序排序并取所有
        LinkedHashMap<String, BigDecimal> topAllMarkupSectorHashMap = markupSectorHashMap
                .entrySet()
                .stream()
                .sorted(Map.Entry.<String, BigDecimal>comparingByValue()
                        .reversed())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldVal, newVal) -> oldVal, LinkedHashMap::new));

        //查询所有板块的股票
        //主板判断值
        BigDecimal mainSectorBigDecimal = new BigDecimal(9.50);
        //创业板判断值
        BigDecimal secondSectorBigDecimal = new BigDecimal(9.50);
        //统计板块涨幅排序涨停股票
        HashMap<String, List<Object[]>> sectorMarkupSortStockHashMap = new HashMap<>();

        //统计板块涨幅排序涨停股票所有
        HashMap<String, List<Object[]>> sectorALLMarkupSortStockHashMap = new HashMap<>();

        //统计板块龙头所有
        HashMap<String, List<Object[]>> sectorAllDragonSortStockHashMap = new HashMap<>();

        //统计板块涨停个数股票排序涨停排序
        HashMap<String, List<Object[]>> sectorMarkupStockCountSortHashMap = new HashMap<>();

        for (Map.Entry<String, String> CCodeArrayMapEntry : CCodeArrayMap.entrySet()) {
            String CCode = CCodeArrayMapEntry.getKey();
            String threeUrl = "https://apphwhq.longhuvip.com/w1/api/index.php";
            String threeJson = "Order=1&TSZB=0&a=ZhiShuStockList_W8&st=30&c=ZhiShuRanking&PhoneOSNew=1&RStart=0925&old=1&DeviceID=c6b240b6-aa62-371d-9f1b-45c09dff494e&VerSion=5.18.0.2&IsZZ=0&Token=d3ba72277b381ee11f3b9f3087e1cee8&Index=0&REnd=1500&apiv=w39&Type=-4&IsKZZType=0&UserID=2692604&PlateID=" + CCode + "&TSZB_Type=0&filterType=0&";
            // 设置请求头
            HashMap<String, String> threeHeaders = new HashMap<>();
            threeHeaders.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            threeHeaders.put("User-Agent", "Dalvik/2.1.0 (Linux; U; Android 9; NX627J Build/PQ3B.190801.01161429)");
            threeHeaders.put("Host", "apphwhq.longhuvip.com");
            threeHeaders.put("Connection", "Keep-Alive");
            threeHeaders.put("Accept-Encoding", "gzip");
            String threeContent = null;
            try {
                threeContent = HttpClientUtil.doPost(threeUrl, threeJson, threeHeaders);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            JSONObject threeJsonObject = JSON.parseObject(threeContent);
            JSONArray threeListJSONArray = threeJsonObject.getJSONArray("list");
            for (int j = 0; j < threeListJSONArray.size(); j++) {
                JSONArray childArray = threeListJSONArray.getJSONArray(j);
                String stockCode = (String) childArray.get(0);
                String stockName = (String) childArray.get(1);
                String dragon = (String) childArray.get(24);
                Object o = childArray.get(6);
                BigDecimal markup = new BigDecimal(o.toString());

                //主板
                if (markup.compareTo(mainSectorBigDecimal) >= 0 && !stockCode.startsWith("30") && !stockCode.startsWith("688")) {
                    Object[] objects = new Object[3];
                    objects[0] = stockCode;
                    objects[1] = stockName;
                    objects[2] = markup;

                    //主板：降序排序并取前4
                    if (!stockCode.startsWith("30") && !stockCode.startsWith("688")
                            && !stockCode.startsWith("4") && !stockCode.startsWith("8") && !stockCode.startsWith("9")) {
                        if (top4MarkupSectorHashMap.containsKey(CCode)) {
                            List<Object[]> sectorMarkupSortStockHashMapList = sectorMarkupSortStockHashMap.getOrDefault(CCode, new ArrayList<>());
                            sectorMarkupSortStockHashMapList.add(objects);
                            sectorMarkupSortStockHashMap.put(CCode, sectorMarkupSortStockHashMapList);
                        }
                        //统计板块涨停个数股票排序涨停排序
                        List<Object[]> sectorMarkupStockCountSortHashMapList = sectorMarkupStockCountSortHashMap.getOrDefault(CCode, new ArrayList<>());
                        sectorMarkupStockCountSortHashMapList.add(objects);
                        sectorMarkupStockCountSortHashMap.put(CCode, sectorMarkupStockCountSortHashMapList);
                    }

                    //主板：降序排序并取所有
                    if (!stockCode.startsWith("30") && !stockCode.startsWith("688")
                            && !stockCode.startsWith("4") && !stockCode.startsWith("8") && !stockCode.startsWith("9")) {
                        if (topAllMarkupSectorHashMap.containsKey(CCode)) {
                            List<Object[]> sectorMarkupSortStockHashMapList = sectorALLMarkupSortStockHashMap.getOrDefault(CCode, new ArrayList<>());
                            sectorMarkupSortStockHashMapList.add(objects);
                            sectorALLMarkupSortStockHashMap.put(CCode, sectorMarkupSortStockHashMapList);
                        }
                    }

                    //主板：统计板块龙头所有
                    Object[] twoObjects = new Object[4];
                    //股票代码
                    twoObjects[0] = stockCode;
                    //股票名称
                    twoObjects[1] = stockName;
                    //股票涨幅
                    twoObjects[2] = markup;
                    //龙头几
                    twoObjects[3] = dragon;

                    if (!stockCode.startsWith("30") && !stockCode.startsWith("688")
                            && !stockCode.startsWith("4") && !stockCode.startsWith("8") && !stockCode.startsWith("9")) {
                        if (topAllMarkupSectorHashMap.containsKey(CCode)) {
                            List<Object[]> sectorAllDragonSortStockHashMapList = sectorAllDragonSortStockHashMap.getOrDefault(CCode, new ArrayList<>());
                            sectorAllDragonSortStockHashMapList.add(twoObjects);
                            sectorAllDragonSortStockHashMap.put(CCode, sectorAllDragonSortStockHashMapList);
                        }
                    }

                }


                //创业板：降序排序并取前4
                if (markup.compareTo(secondSectorBigDecimal) >= 0 && stockCode.startsWith("30")) {
                    Object[] objects = new Object[3];
                    objects[0] = stockCode;
                    objects[1] = stockName;
                    objects[2] = markup;

                    //降序排序并取前4
                    if (top4MarkupSectorHashMap.containsKey(CCode)) {
                        List<Object[]> sectorMarkupSortStockHashMapList = sectorMarkupSortStockHashMap.getOrDefault(CCode, new ArrayList<>());
                        sectorMarkupSortStockHashMapList.add(objects);
                        sectorMarkupSortStockHashMap.put(CCode, sectorMarkupSortStockHashMapList);
                    }

                    //降序排序并取所有
                    if (topAllMarkupSectorHashMap.containsKey(CCode)) {
                        List<Object[]> sectorMarkupSortStockHashMapList = sectorALLMarkupSortStockHashMap.getOrDefault(CCode, new ArrayList<>());
                        sectorMarkupSortStockHashMapList.add(objects);
                        sectorALLMarkupSortStockHashMap.put(CCode, sectorMarkupSortStockHashMapList);
                    }

                    //主板：统计板块龙头所有
                    Object[] twoObjects = new Object[4];
                    //股票代码
                    twoObjects[0] = stockCode;
                    //股票名称
                    twoObjects[1] = stockName;
                    //股票涨幅
                    twoObjects[2] = markup;
                    //龙头几
                    twoObjects[3] = dragon;
                    if (topAllMarkupSectorHashMap.containsKey(CCode)) {
                        List<Object[]> sectorAllDragonSortStockHashMapList = sectorAllDragonSortStockHashMap.getOrDefault(CCode, new ArrayList<>());
                        sectorAllDragonSortStockHashMapList.add(twoObjects);
                        sectorAllDragonSortStockHashMap.put(CCode, sectorAllDragonSortStockHashMapList);
                    }


                    //统计板块涨停个数股票排序涨停排序
                    List<Object[]> sectorMarkupStockCountSortHashMapList = sectorMarkupStockCountSortHashMap.getOrDefault(CCode, new ArrayList<>());
                    sectorMarkupStockCountSortHashMapList.add(objects);
                    sectorMarkupStockCountSortHashMap.put(CCode, sectorMarkupStockCountSortHashMapList);
                }

            }
        }

        //统计板块涨幅排序涨停股票取前四
        String sectorMarkupSortStockString = new String();
        for (Map.Entry<String, BigDecimal> entry : top4MarkupSectorHashMap.entrySet()) {
            String CCode = entry.getKey();
            String CName = CCodeArrayMap.get(CCode);
            List<Object[]> objectsList = sectorMarkupSortStockHashMap.get(CCode);
            if (objectsList != null) {
                sectorMarkupSortStockString += "<p><b>" + CName + "(" + objectsList.size() + "只):</b>&nbsp;&nbsp;&nbsp;";
                for (int i = 0; i < objectsList.size(); i++) {
                    Object[] objects = objectsList.get(i);
                    String stockName = (String) objects[1];
                    BigDecimal markup = (BigDecimal) objects[2];
                    if (i == objectsList.size() - 1) {
                        sectorMarkupSortStockString += stockName + " " + markup + "%" + "&nbsp;&nbsp;&nbsp;</p>";
                    } else {
                        sectorMarkupSortStockString += stockName + " " + markup + "%" + "&nbsp;&nbsp;&nbsp;";
                    }
                }
            }
        }

        //统计板块涨幅排序涨停股票取所有
        String sectorAllMarkupSortStockString = new String();
        //开盘啦热门题材详细显示全部
        String popularTopicsDetailShowAllString = new String();
        for (Map.Entry<String, BigDecimal> entry : topAllMarkupSectorHashMap.entrySet()) {
            String CCode = entry.getKey();
            String CName = CCodeArrayMap.get(CCode);
            List<Object[]> objectsList = sectorALLMarkupSortStockHashMap.get(CCode);
            if (objectsList != null) {
                System.out.println();
                sectorAllMarkupSortStockString += "<p><b>" + CName + "(" + objectsList.size() + "只):</b>&nbsp;&nbsp;&nbsp;";
                for (int i = 0; i < objectsList.size(); i++) {
                    Object[] objects = objectsList.get(i);
                    String stockName = (String) objects[1];
                    BigDecimal markup = (BigDecimal) objects[2];
                    if (i == objectsList.size() - 1) {
                        sectorAllMarkupSortStockString += stockName + " " + markup + "%" + "&nbsp;&nbsp;&nbsp;</p>";
                    } else {
                        sectorAllMarkupSortStockString += stockName + " " + markup + "%" + "&nbsp;&nbsp;&nbsp;";
                    }

                }
                //板块爆发原因
                String fourUrl = "https://apphwhq.longhuvip.com/w1/api/index.php";
                String fourJson = "a=GetBaseFaceListZDEvnArtNew&apiv=w40&c=ZhiShuL2Data&StockID=" + CCode + "&PhoneOSNew=1&DeviceID=c6b240b6-aa62-371d-9f1b-45c09dff494e&VerSion=5.19.0.0&";
                // 设置请求头
                HashMap<String, String> fourHeaders = new HashMap<>();
                fourHeaders.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                fourHeaders.put("User-Agent", "Dalvik/2.1.0 (Linux; U; Android 9; NX627J Build/PQ3B.190801.01161429)");
                fourHeaders.put("Host", "apphwhq.longhuvip.com");
                fourHeaders.put("Connection", "Keep-Alive");
                fourHeaders.put("Accept-Encoding", "gzip");
                String fourContent = null;
                try {
                    fourContent = HttpClientUtil.doPost(fourUrl, fourJson, fourHeaders);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                if (StringUtils.isNotEmpty(fourContent)) {
                    JSONObject fourJsonObject = JSON.parseObject(fourContent);
                    //爆发时间
                    String date = fourJsonObject.getString("Date");
                    //爆发原因
                    String boomReason = fourJsonObject.getString("BoomReason");

                    String endString = CName + ": " + date + " " + boomReason + "; ";
                    popularTopicsDetailShowAllString += endString;
                }
            }

        }


        //统计板块龙头所有
        String sectorAllDragonSortStockString = new String();
        for (Map.Entry<String, BigDecimal> entry : topAllMarkupSectorHashMap.entrySet()) {
            String CCode = entry.getKey();
            String CName = CCodeArrayMap.get(CCode);
            List<Object[]> objectsList = sectorAllDragonSortStockHashMap.get(CCode);
            if (objectsList != null) {
                sectorAllDragonSortStockString += "<p><b>" + CName + "(" + objectsList.size() + "只):</b>&nbsp;&nbsp;&nbsp;";
                for (int i = 0; i < objectsList.size(); i++) {
                    Object[] objects = objectsList.get(i);
                    String stockName = (String) objects[1];
                    BigDecimal markup = (BigDecimal) objects[2];
                    String dragonString = (String) objects[3];
                    String dragon = StringUtils.isNotEmpty(dragonString) ? dragonString + " " : "";
                    if (i == objectsList.size() - 1) {
                        sectorAllDragonSortStockString += stockName + " " + dragon + markup + "%" + "&nbsp;&nbsp;&nbsp;</p>";
                    } else {
                        sectorAllDragonSortStockString += stockName + " " + dragon + markup + "%" + "&nbsp;&nbsp;&nbsp;";
                    }
                }
            }
        }


        //统计板块涨停个数股票排序涨停排序前四
        String sectorMarkupStockCountSortHashMapEntryString = new String();
        // 按集合大小降序排序，取前4项
        Map<String, List<Object[]>> sectorMarkupStockCountSortHashMapSort = sectorMarkupStockCountSortHashMap
                .entrySet()
                .stream()
                .sorted((e1, e2) -> Integer.compare(e2.getValue().size(), e1.getValue().size())) // 降序
                .limit(4) // 取前4项
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldVal, newVal) -> oldVal, LinkedHashMap::new // 保持顺序
                ));
        for (Map.Entry<String, List<Object[]>> sectorMarkupStockCountSortHashMapEntry : sectorMarkupStockCountSortHashMapSort.entrySet()) {
            String CCode = sectorMarkupStockCountSortHashMapEntry.getKey();
            String CName = CCodeArrayMap.get(CCode);
            List<Object[]> objectsList = sectorMarkupStockCountSortHashMapEntry.getValue();
            if (objectsList != null) {
                sectorMarkupStockCountSortHashMapEntryString += "<p><b>" + CName + "(" + objectsList.size() + "只):</b>&nbsp;&nbsp;&nbsp;";
                for (int i = 0; i < objectsList.size(); i++) {
                    Object[] objects = objectsList.get(i);
                    String stockName = (String) objects[1];
                    BigDecimal markup = (BigDecimal) objects[2];

                    if (i == objectsList.size() - 1) {
                        sectorMarkupStockCountSortHashMapEntryString += stockName + " " + markup + "%" + "&nbsp;&nbsp;&nbsp;</p>";
                    } else {
                        sectorMarkupStockCountSortHashMapEntryString += stockName + " " + markup + "%" + "&nbsp;&nbsp;&nbsp;";
                    }
                }
            }
        }

        String[] strings = new String[5];
        strings[0] = sectorMarkupSortStockString;
        strings[1] = sectorAllMarkupSortStockString;
        strings[2] = sectorMarkupStockCountSortHashMapEntryString;
        strings[3] = popularTopicsDetailShowAllString;
        strings[4] = sectorAllDragonSortStockString;
        return strings;
    }
}
